package com.member.mp.filter;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.member.common.constant.RequestStatusConst;
import com.member.common.constant.SystemConst;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.utils.RmRequestWrapper;
import com.member.shop.domain.SysBizUser;
import com.member.shop.service.ISysBizUserService;
import com.member.system.cache.TokenCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * @author wangxin
 */
@Order(1)
@Slf4j
@Component
public class RequestFilter implements Filter {
    static String[] excludedPaths = new String[]{
            "/mp-api/wx",
            "/mp-api/wx/common",
            "/mp-api/swagger",
            "/mp-api/v3",
            "/mp-api/wx/index",
            "/mp-api/wx/activity/queryActivityAll",
            "/mp-api/wx/activity/queryActivityById",
            "/mp-api/wx/goods/queryFirstCategory",
            "/mp-api/wx/goods/queryGoodsDetail",
            "/mp-api/wx/goods/queryGoodsEvaluateByGoodsId",
            "/mp-api/wx/pay/payOrder",             // 微信支付
            "/mp-api/wx/payment/callbackByOrder",  // 微信支付回调
            "/mp-api/wx/payment/callbackBySurplus",// 微信支付回调
            "/mp-api/wx/alipay",
            "/mp-api/wx/auth",
            "/mp-api/wx/order/testOpenAccount",
            "/mp-api/wx/order/createBank",
            "/mp-api/wx/order/balanceAllocate",
            "/mp-api/wx/user/queryAgreement",
            "/mp-api/wx/hIndex",
            "/mp-api/wx/platform",
            "/mp-api/wx/activity/saleActivity",
            "/mp-api/wx/platform/queryTenantList",
            "/mp-api/wx/goods/queryGoodsByRecommend",
            "/mp-api/wx/goods/queryGoods"
    };

    @Resource
    private ISysBizUserService sysBizUserService;

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("RequestFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        RmRequestWrapper requestWrapper = null;
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String path = request.getRequestURI();
            String token = request.getHeader(SystemConst.TOKEN);
            if (StringUtils.isEmpty(token)) {
                token = request.getParameter(SystemConst.TOKEN);
            } else {
                token = token.replace("Bearer ", StringUtils.EMPTY);
            }
            log.info("path:" + path + ",token:" + token);
            String loginDatas = "";
            if (!path.startsWith("/mp-api/wx/auth")) {
                if (!StringUtils.isEmpty(token)) {
                    loginDatas = TokenCache.getMpData(token);
                    if (!StringUtils.isEmpty(loginDatas)) {
                        SysBizUser sysBizUser = JSON.parseObject(loginDatas, SysBizUser.class);
                        SysBizUser user = sysBizUserService.selectSysBizUserById(sysBizUser.getId());
                        if (user!=null && (user.getDisplayed() == 1 || user.getDeleted() == 1 || user.getReLogin() == 2)) {
                            HttpServletResponse response = (HttpServletResponse) servletResponse;
                            response.setStatus(RequestStatusConst.DISABLED);
                            sysBizUserService.update(new LambdaUpdateWrapper<SysBizUser>()
                                    .eq(SysBizUser::getId, sysBizUser.getId())
                                    .set(SysBizUser::getReLogin, 1));
                            TokenCache.removeMpData(token);
                            return;
                        }
                    }else{
                        HttpServletResponse response = (HttpServletResponse) servletResponse;
                        response.setStatus(RequestStatusConst.DISABLED);
                        return;
                    }
                }
            }
            boolean excluded = false;
            for (String excludedUrl : excludedPaths) {
                if (path.startsWith(excludedUrl)) {
                    excluded = true;
                    break;
                }
            }
            TreeMap<String, Object> paramsMaps = new TreeMap<>();
            // 获取请求参数
            requestWrapper = new RmRequestWrapper(request);
            Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
            Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
            for (Map.Entry<String, String[]> next : entries) {
                paramsMaps.put(next.getKey(), next.getValue()[0]);
            }
            log.info("parameterMap:" + paramsMaps);
            if (excluded) {
                filterChain.doFilter(requestWrapper, servletResponse);
                return;
            }
            String loginData = "";
            if (StringUtils.isEmpty(token)) {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.setStatus(RequestStatusConst.NOT_TOKEN);
                return;
            }
            loginData = TokenCache.getMpData(token);
            if (StringUtils.isEmpty(loginData)) {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.setStatus(RequestStatusConst.NOT_TOKEN);
                return;
            }
            // 后台删除用户
            SysBizUser sysBizUser = JSON.parseObject(loginDatas, SysBizUser.class);
            SysBizUser user = sysBizUserService.getById(sysBizUser.getId());
            if (user == null || user.getDeleted().equals(OrderDeleteEnum.DELETE.getKey())) {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.setStatus(RequestStatusConst.NOT_TOKEN);
                return;
            }
            // 后台修改用户手机号
            if (!user.getUserPhone().equals(sysBizUser.getUserPhone())) {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.setStatus(RequestStatusConst.NOT_TOKEN);
                return;
            }
            // 后台重置用户密码
            if (StringUtils.isNotBlank(sysBizUser.getPassword())
                    && StringUtils.isNotBlank(user.getPassword())
                    && !user.getPassword().equals(sysBizUser.getPassword())) {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.setStatus(RequestStatusConst.NOT_TOKEN);
                return;
            }
            TokenCache.setMpTokenExpire(token);
            if (SystemConst.GET.equalsIgnoreCase(request.getMethod())) {
                filterChain.doFilter(requestWrapper, servletResponse);
                return;
            }
        }
        if (requestWrapper == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }


    @Override
    public void destroy() {
        log.info("RequestFilter destroy");
    }

}

